<template>
  <div>
    <h2>评论区</h2>
    <a-textarea
      v-model="newComment"
      :autosize="{ minRows: 3, maxRows: 5 }"
      placeholder="请分享你的想法..."
      style="min-height: 76px"
    />
    <a-button type="primary" @click="handleCommentSubmit"> 发表评论</a-button>

    <a-list style="margin-top: 20px; border: none; background: none">
      <a-list-item v-for="item in comments" :key="item.id">
        <a-comment>
          <div class="comment-header">
            <img
              :src="item.userAvatar || defaultAvatar"
              class="avatar"
              alt="头像"
            />
            <span class="username">{{ item.userName }}</span>
            <span class="timestamp">{{ formatTime(item.createTime) }}</span>
          </div>
          <p>{{ item.content }}</p>
        </a-comment>
      </a-list-item>
    </a-list>
    <div class="pagination-controls">
      <a-pagination
        v-model:value="comments"
        v-model:current="currentPage"
        :total="totalRecords"
        :page-size="commentsPerPage"
        @change="fetchComments"
        simple
      ></a-pagination>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import {
  CommentAddRequest,
  CommentControllerService,
  CommentQueryRequest,
  CommentVO,
} from "../../generated";
import { withDefaults, defineProps } from "vue";
import { useStore } from "vuex";
import message from "@arco-design/web-vue/es/message";

interface Props {
  questionId: number;
}

const props = withDefaults(defineProps<Props>(), {
  questionId: () => 0,
});

// 分页状态
const currentPage = ref(1);
const commentsPerPage = 2; // 每页评论数
const totalRecords = ref(0); // 总评论数

// 计算总页数
const totalPages = computed(() =>
  Math.ceil(totalRecords.value / commentsPerPage)
);

// 计算当前页的评论
const paginatedComments = computed(() => {
  return comments.value;
});

const newComment = ref("");
const comments = ref<CommentVO[]>();
const fetchComments = async () => {
  const request: CommentQueryRequest = {
    current: currentPage.value,
    pageSize: commentsPerPage,
    questionId: props.questionId,
  };
  const res = await CommentControllerService.listCommentVoByPageUsingPost(
    request
  );
  if (res.code === 0) {
    const data = res.data;
    comments.value = data.records || [];
    totalRecords.value = data.total || 0; // 设置总记录数
  }
};
// 页码切换函数
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchComments(); // 每次切换页码时重新获取评论
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchComments(); // 每次切换页码时重新获取评论
  }
};
// 在组件加载时获取评论
fetchComments();

const store = useStore();
console.log("评论用户id   =====> ", store.state.user?.loginUser.id);
console.log("questionId ===> ", props.questionId);

const defaultAvatar = "https://example.com/default-avatar.png"; // 替换为你的默认头像 URL

const handleCommentSubmit = async () => {
  // todo 以后用websocket来进行交流
  // let websocket: WebSocket;
  // websocket = new WebSocket("ws://localhost:8121/api/webSocket"); // 替换为你的 WebSocket 地址
  //
  // websocket.onopen = () => {
  //   console.log("WebSocket 连接已建立");
  // };
  //
  // websocket.onmessage = (event) => {
  //   const messageData = JSON.parse(event.data);
  //   // 假设 messageData 是一条评论
  //   // comments.value.push(messageData);
  // };
  // // 发送消息函数
  // const sendMessage = (message) => {
  //   if (websocket.readyState === WebSocket.OPEN) {
  //     websocket.send(JSON.stringify(message));
  //   } else {
  //     console.error("WebSocket 连接未建立");
  //   }
  // };
  //
  // websocket.onclose = () => {
  //   console.log("WebSocket 连接已关闭");
  // };
  //
  // websocket.onerror = (error) => {
  //   console.error("WebSocket 发生错误:", error);
  // };
  console.log("提交评论:", newComment.value);
  console.log("questionId ===> ", props.questionId);
  const res = await CommentControllerService.addCommentUsingPost({
    content: newComment.value,
    questionId: props.questionId,
    userId: store.state.user?.loginUser.id,
  });
  if (res.code === 0) {
    newComment.value = "";
    message.success("评论成功!!!");
    fetchComments();
  }
};
// 时间格式化函数
const formatTime = (timestamp: string): string => {
  const now = new Date();
  const past = new Date(timestamp);

  const seconds = Math.floor((now.getTime() - past.getTime()) / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);

  if (seconds < 60) {
    return `${seconds} 秒前`;
  } else if (minutes < 60) {
    return `${minutes} 分钟前`;
  } else if (hours < 24) {
    return `${hours} 小时前`;
  } else {
    return `${days} 天前`;
  }
};
</script>

<style scoped>
/* 添加一些基本样式 */
h2 {
  margin-bottom: 16px;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.avatar {
  width: 32px; /* 设置头像大小 */
  height: 32px;
  border-radius: 50%; /* 圆形头像 */
  margin-right: 8px; /* 头像与用户名之间的间距 */
}

.username {
  font-weight: bold;
  margin-right: auto; /* 自动右边距将时间戳推到最右边 */
}

.timestamp {
  font-size: 0.9em; /* timestamp 字体小一点 */
  color: #999; /* 时间戳字体颜色 */
}
</style>
